/*************************************************************************
	> File Name: CalcClient.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/18 16:40
 ************************************************************************/

#include <unistd.h>
#include "Sock.hpp"
#include "Protocol.hpp"

static void Usage(const std::string& proc) {
    std::cout << "\nUsage:" << proc << " ip port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3) {
        Usage(argv[0]);
        exit(1);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);
    halil::Sock sock;
    int sockfd = sock.Socket();
    if (!sock.Connect(sockfd, server_ip, server_port)) {
        std::cerr << "Connect error" << std::endl;
        exit(2);
    }
    bool quit = false;
    std::string buffer;
    while (!quit) {
        halil::Request req;
        std::cout << "Please Enter # " << std::endl;
        std::cin >> req._x >> req._op >> req._y;
        std::string s = req.Serialize();
        s = halil::Encode(s);
        halil::Send(sockfd, s);
        if (!halil::Recv(sockfd, &buffer)) {
            quit = true;
            break;
        }
        std::string package = halil::Decode(buffer);
        if (package.empty()) {
            continue;
        }
        halil::Response resp;
        resp.Deserialized(package);
        std::string err;
        switch (resp._code) {
            case 1:
            err = "Divide 0 error";
            break;
            case 2:
            err = "Mode 0 error";
            break;
            case 3:
            err = "Illegal operation";
            break;
            default:
            std::cout << "result = " << resp._result << std::endl;
            break;
        }
    }
    close(sockfd);
    return 0;
}
